package com.jyy.prefabricated.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jyy.prefabricated.dto.TaxResult;
import com.jyy.prefabricated.dto.UmsEnterPriseInfoVo;
import com.jyy.prefabricated.properties.CommonProperties;
import com.jyy.prefabricated.utils.HttpHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.HttpHead;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

/**
 * @author zhangyang
 * @date 2020/4/15.
 */
@Component
@Slf4j
public class QichachaService {

    @Autowired
    private CommonProperties commonProperties;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 查询企业信息
     * @param companyName
     * @return
     */
    public UmsEnterPriseInfoVo getTaxResult(String companyName) {
        if (StringUtils.isEmpty(companyName)) return null;
        String reqInterNme = "http://api.qichacha.com/ECICreditCode/GetCreditCodeNew";
        String paramStr = "keyword=" + companyName;
        try {
            // auth header setting
            HttpHead reqHeader = new HttpHead();
            String[] autherHeader = RandomAuthentHeader();
            reqHeader.setHeader("Token", autherHeader[0]);
            reqHeader.setHeader("Timespan", autherHeader[1]);
            final String reqUri = reqInterNme.concat("?key=").concat(commonProperties.getQichachaKey()).concat("&").concat(paramStr);
            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
            //out.println(String.format("==========================>this is response:{%s}", tokenJson));
            log.info("tokenJson[{}]", tokenJson);


            // parse status from json
            TaxResult taxResult = objectMapper.readValue(tokenJson, TaxResult.class);
            //status = FormartJson(tokenJson, "Status");
            log.info("taxResult status[{}],companyName[{}]", taxResult.getStatus(), companyName);
            //out.println(String.format("==========================>Status:{%s}", status));
            if (!HttpCodeRegex.isAbnornalRequest(taxResult.getStatus())) {
                return taxResult.getResult();
            }
        } catch (Exception e1) {
            log.error("tax parse error companyName {}", companyName,  e1);
        }
        return null;
    }

    // 获取返回码 Res Code
    static class HttpCodeRegex {
        private static final String ABNORMAL_REGIX = "(101)|(102)";
        private static final Pattern pattern = Pattern.compile(ABNORMAL_REGIX);
        protected static boolean isAbnornalRequest(final String status) {
            return pattern.matcher(status).matches();
        }
    }

    // 获取Auth Code
    protected  String[] RandomAuthentHeader() {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        String[] authentHeaders = new String[] { DigestUtils.md5Hex(commonProperties.getQichachaKey().concat(timeSpan).concat(commonProperties.getQichachaSecret())).toUpperCase(), timeSpan };
        return authentHeaders;
    }
}
